<?php
/************************************************************
** @Description: 使用PHP将html转word
** @Author: georgehao
** @Date:   2019-01-10 15:47:23
** @Last Modified by:   georgehao
** @Last Modified time: 2019-01-11 10:05:57
*************************************************************/
$title = "word";
$html  = '<h1>中文的标题，技术无止境，一直在路上</h1>
<p>p是可以分段的. 使用PHP将html转word</p>
<p>再分一段 使用PHP将html转word</p>
<p>还分一段，下面加个图片</p>
<img alt="" class="has" src="http://www.ibp.cas.cn/kyjz/zxdt/201901/W020190103493057285919.jpg">
<style>
.testclass{
    font-size:30px;
    color:#ff0000;
}
</style>
<div class="testclass">class样式样式是否可以</div>
<div style="color:#999fff">测试行内样式</div>
';
//使用方法-------------------------
echo (cword($html,$title));
echo createWord($html); 
//----------------------------------------
function cword($data,$fileName='')
{
    if(empty($data)) return '';
    $data = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:w="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">'.$data.'</html>';
    $dir  = "./dir/";
    if(!file_exists($dir)) mkdir($dir,777,true);
    if(empty($fileName)){
        $fileName=$dir.date('His').'.doc';
    }else{
        $fileName =$dir.$fileName.'.doc';
    }
    $writefile = fopen($fileName,'wb') or die("创建文件失败"); //wb以二进制写入
    fwrite($writefile,$data);
    fclose($writefile);
    return $fileName;
}
function createWord($content='')
    {
        
        // die;
        if(empty($content)){
            return;
        }
        $content='<html 
                xmlns:o="urn:schemas-microsoft-com:office:office" 
                xmlns:w="urn:schemas-microsoft-com:office:word" 
                xmlns="http://www.w3.org/TR/REC-html40">
                <meta charset="UTF-8" />'.$content.'</html>';
        if(empty($fileName)){
            $fileName=date('YmdHis').'.html';
        }
        $fp=fopen('./dir/'.$fileName,'wb');
        fwrite($fp,$content);
        fclose($fp);
        // return $fileName;
        // echo './Upload/Wsj/'.$fileName;
        return $fileName;
       
    }